<?php

/***
 * The following constants are used within the log class,
 * so let's make sure they exist:
 ***/

if(false == defined('LOG_ACTIVE'))
{
	define('LOG_ACTIVE', true);
}

if(false == defined('LOG_VERBOSE'))
{
	define('LOG_VERBOSE', false);
}

if(false == defined('LOG_EMAIL_NOTIFY'))
{
	define('LOG_EMAIL_NOTIFY', true);
}

if(false == defined('LOG_EMAIL_ADDRESS'))
{
	define('LOG_EMAIL_ADDRESS', '');
}

if(false == defined('PATH_LOGS'))
{
	define('PATH_LOGS', getcwd());
}

class CW_LogClass {

	const LOG_ACTIVE = LOG_ACTIVE;
	const LOG_VERBOSE = LOG_VERBOSE;
	const LOG_EMAIL_NOTIFY = LOG_EMAIL_NOTIFY;
	const LOG_EMAIL_ADDRESS = LOG_EMAIL_ADDRESS;
	const LOG_PATH = PATH_LOGS;

	static function add($message, $file = __FILE__, $line = __LINE__, $level = 3)
	{
		if(false == self::LOG_ACTIVE)
		{
			return false;
		}


		if(false == is_dir(self::LOG_PATH))
		{
			throw new CoreException("Could not open today's log file.");
		}


		if(false == is_writable(self::LOG_PATH))
		{
			throw new CoreException("Log path '" . self::LOG_PATH . "' is not writable.");
		}


		$pointer = fopen(self::LOG_PATH . DIRECTORY_SEPARATOR . 'log-' . date('Y-m-d', time()) . '.txt', 'a');


		switch($level)
		{
			default:
			case 1: $literal_error_type = 'User Error'; break;
			case 2: $literal_error_type = 'Warning'; break;
			case 3: $literal_error_type = 'Fatal Error'; break;
		}


		if(self::LOG_VERBOSE)
		{
			ob_start();

			debug_print_backtrace();

			$backtrace = ob_get_contents();

			ob_end_clean();

			$entry  = "{$literal_error_type} Found:\n";
			$entry .= "----------------------------------------------------------\n";
			$entry .= "At " . date(DATE_ATOM, time()) . "\n";
			$entry .= "In {$file} {line: {$line}}\n";
			$entry .= "From {$_SERVER['REMOTE_ADDR']} {{$_SERVER['HTTP_USER_AGENT']}}\n";
			$entry .= "----------------------------------------------------------\n";
			$entry .= "Message:\n\n";
			$entry .= "{$message}\n\n";
			$entry .= "----------------------------------------------------------\n";
			$entry .= "Backtrace:\n\n";
			$entry .= trim($backtrace) . "\n\n";
			$entry .= "----------------------------------------------------------\n\n\n";
		}
		else
		{
			$entry = date(DATE_ATOM, time()) . ": {$message} {$file} {line: {$line}}\n";
		}


		fwrite($pointer, $entry);
		fclose($pointer);


		if(self::LOG_EMAIL_NOTIFY && self::LOG_EMAIL_ADDRESS)
		{
			$message = "The following error was found:\n";
			$message .= "----------------------------------------------------------\n";
			$message .= $entry;

			if(mail(self::LOG_EMAIL_ADDRESS, 'Exception found ' .date(DATE_ATOM, time()), $message))
			{
				throw new CoreException("Could not email fatal error log entry...");
			}
		}

		return true;
	}
}

?>